package com.umbacos.udm.client.arch;

import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

public class ContextMenu extends PopupPanel implements ContextMenuList {

	public int count=0;
	private VerticalPanel vp = new VerticalPanel();;
	private EventHandler handlerOwner=null;
	private int rowIndex;
	private int cellIndex;
	
	public ContextMenu() {
        super(true);
        vp.setStyleName("contextmenu");
        this.add(vp);
      }

	public void addEventHandler(EventHandler handlerOwner){
        this.handlerOwner=handlerOwner;
	}

	public void add(int command, ImageButton icon, Label label){
        vp.add(new MenuItem(command, icon, label));
	}
	
	public int getMenuItemCount(){
        return vp.getWidgetCount();
	}
	
	public int getCellIndex() {
		return cellIndex;
	}

	public int getRowIndex() {
		return rowIndex;
	}

	public void setCellIndex(int cellIndex) {
		this.cellIndex=cellIndex;
	}

	public void setRowIndex(int rowIndex) {
		this.rowIndex=rowIndex;
	}

	class MenuItem extends HorizontalPanel {

		int command;
		
		public MenuItem (int command, ImageButton icon, Label caption) {
			super();

			this.command = command;
			setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
			icon.setStyleName("menuicon");
			caption.setWidth("250px");
	        add(icon);
	        add(new HTML("&nbsp;&nbsp;"));
	        add(caption);
	        sinkEvents(Event.MOUSEEVENTS + Event.ONCLICK + Event.ONCONTEXTMENU);
		}
		
	    public void onBrowserEvent(Event event)
	    {
	        switch(DOM.eventGetType(event))
	        {
	        case Event.ONMOUSEOVER:
				((ImageButton)this.getWidget(0)).onMouseOver(null);
				this.addStyleName("contextmenuhover");
	            break;
	        case Event.ONMOUSEOUT:
				((ImageButton)this.getWidget(0)).onMouseOut(null);
				this.removeStyleName("contextmenuhover");
	            break;
	        case Event.ONCLICK:
	        	if (handlerOwner != null) {
					handlerOwner.contextMenuClickCallback(command, rowIndex, cellIndex);
					handlerOwner = null;
	        	}
				hide();
	            break;
	        case Event.ONCONTEXTMENU:
	        	event.stopPropagation();
	        	break;
	        default:
	            break;
	        }
	    }
	}
	
	public interface EventHandler {
		public void contextMenuClickCallback(int command, int rowIndex, int cellindex);
	}
}
